/**
 * API接口统一管理
 */

import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
import router from '../router'
import type { ApiResponse } from '@/types'

// 创建axios实例
const api: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器
api.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // 添加认证token
    const token = localStorage.getItem('access_token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse) => {
    return response
  },
  (error) => {
    // 处理HTTP错误
    if (error.response) {
      const { status, data } = error.response

      switch (status) {
        case 401:
          // 未授权，清除token并跳转到登录页
          localStorage.removeItem('access_token')
          localStorage.removeItem('refresh_token')
          router.push('/login')
          ElMessage.error('登录已过期，请重新登录')
          break
        case 403:
          ElMessage.error('没有权限访问此资源')
          break
        case 404:
          ElMessage.error('请求的资源不存在')
          break
        case 500:
          ElMessage.error('服务器内部错误')
          break
        default:
          if (data?.message) {
            ElMessage.error(data.message)
          } else {
            ElMessage.error(`请求失败 (${status})`)
          }
      }
    } else if (error.request) {
      ElMessage.error('网络错误，请检查网络连接')
    } else {
      ElMessage.error('请求发生错误')
    }

    return Promise.reject(error)
  }
)

// 通用请求方法
export const request = async <T = any>(
  config: AxiosRequestConfig
): Promise<ApiResponse<T>> => {
  try {
    const response = await api(config)
    return {
      code: response.status,
      message: response.statusText,
      data: response.data,
      success: true
    }
  } catch (error: any) {
    // 错误已在拦截器中处理
    throw error
  }
}

// GET请求
export const get = <T = any>(
  url: string,
  params?: any,
  config?: AxiosRequestConfig
): Promise<ApiResponse<T>> => {
  return request<T>({
    method: 'GET',
    url,
    params,
    ...config
  })
}

// POST请求
export const post = <T = any>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<ApiResponse<T>> => {
  return request<T>({
    method: 'POST',
    url,
    data,
    ...config
  })
}

// PUT请求
export const put = <T = any>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<ApiResponse<T>> => {
  return request<T>({
    method: 'PUT',
    url,
    data,
    ...config
  })
}

// DELETE请求
export const del = <T = any>(
  url: string,
  config?: AxiosRequestConfig
): Promise<ApiResponse<T>> => {
  return request<T>({
    method: 'DELETE',
    url,
    ...config
  })
}

// PATCH请求
export const patch = <T = any>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<ApiResponse<T>> => {
  return request<T>({
    method: 'PATCH',
    url,
    data,
    ...config
  })
}

// 导出所有API模块
export * from './auth'
export * from './questions'
export * from './examinations'
export * from './grading'
export * from './examPaper'
export * from './users'

// 重新导出统一的API对象
export { authApi } from './auth'
export { questionApi } from './questions'
export { examinationsApi } from './examinations'
export { gradingApi } from './grading'
export { examPaperApi } from './examPaper'
export { userApi } from './users'

// 为了向后兼容，创建别名
export { examinationsApi as examApi } from './examinations'
export * from './common'

export default api